package com.jnzc.ocr.common.utils;

import java.util.List;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.jnzc.ocr.common.bean.Tree;
import org.apache.commons.collections4.CollectionUtils;

/**
 * TreeUtils.java
 * @author zhangcm 2017-07-05 10:45:01
 * @version 1.0
 */
public class TreeUtils {

    private TreeUtils(){}

    public static <E> Tree<E> createTree(List<E> list, String idAttr, String parentIdAttr, String sortAttr){
        Tree<E> tree = new Tree<E>();
        if(CollectionUtils.isEmpty(list)){
            return tree;
        }
        List<Tree<E>> childrenList = createTreeList(list, idAttr, parentIdAttr, sortAttr, null);
        tree.setChildrenList(childrenList);
        return tree;
    }
    
    public static <E> List<E> toList(Tree<E> tree, Boolean containRoot){
        List<E> result = Lists.newArrayList();
        if(containRoot){
            result.add(tree.getNode());
        }
        List<Tree<E>> childrenList = tree.getChildrenList();
        for (Tree<E> childrenTree : childrenList) {
            List<E> tempList = toList(childrenTree, true);
            result.addAll(tempList);
        }
        return result;
    }

    public static <E> E find(List<Tree<E>> list, Object id){
        for (Tree<E> tree : list) {
            E obj = find(tree, id);
            if(null != obj){
                return obj;
            }
        }
        return null;
    }

    public static <E> E find(Tree<E> tree, Object id){
        if(null != tree.getId() && tree.getId().equals(id)){
            return tree.getNode();
        }
        return find(tree.getChildrenList(), id);
    }
    
    private static <E> List<Tree<E>> createTreeList(List<E> list, String idAttr, String parentIdAttr, String sortAttr, Object id){
        List<Tree<E>> treeList = Lists.newArrayList();
        List<E> dataList = ArrayHandleUtils.readList(list, parentIdAttr, id);
        ArrayHandleUtils.sort(dataList, sortAttr);
        for (E data : dataList) {
            Tree<E> tree = new Tree<E>();
            tree.setId(ArrayHandleUtils.readAttr(data, idAttr));
            tree.setNode(data);
            tree.setSort(ArrayHandleUtils.readAttr(data, sortAttr));
            List<Tree<E>> childrenList = createTreeList(list, idAttr, parentIdAttr, sortAttr, tree.getId());
            tree.setChildrenList(childrenList);
            treeList.add(tree);
        }
        return treeList;
    }
}
